require "Common/define"
require "Logic/Config"
require "Common/functions"
---@class HeadRectItem
HeadRectItem = {}
HelperFunc.SetUIEnv(HeadRectItem)
local this = HeadRectItem;
this.linkColor = "#" .. G.dataTable["t_global"][tostring(185)]["f_string_value"];
this.mainColor = "#" .. G.dataTable["t_global"][tostring(237)]["f_string_value"];
this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;
this.quality = nil;
this.qualityBG = nil;
this.icon = nil;
this.obj_element = nil;
this.element = nil;
this.lv = nil;
this.typeIcon = nil;
this.typeShowController = nil;
this.star = nil;
this.hasUse = nil;
this.hadBattle = nil;
this.hadAssist = nil;
this.choose = nil;
this.unActive = nil;
this.emptyCtrl = nil
this.comIcon = nil
this.circletype = nil
this.useTxt = nil
this.circleCtrl = nil
this.banCtrl = nil
this.useCtrl = nil
this.levelShowCtrl = nil;
this.typeCtrl = nil
local isHopePool;
this.newCtrl = nil
this.hasCtrl = nil
this.hasTxt = nil
this.manorCtrl = nil

--local table_Star = {};

local tab_quality = Config.IconQuality
local tab_frame = Config.IconFrame
local elementName = { "element_1", "element_2", "element_3", "element_4", "element_5" }

function HeadRectItem.Init()
    local name, package = getUIName(PanelNames.HeadRectItem);
    panelMgr:ShowUI(name, package, this.onCreate, Config.useLocalUI);
end

function HeadRectItem.onCreate(obj)
    obj:SetActive(false);
end
---@param obj FairyGUI.GComponent
function HeadRectItem.initData(obj, data, is, fightType, notState, notShowBan, ismy, hothero, iswish, formation_type)
    isHopePool = is;

    --LuaBehaviour = luaBehaviour;
    --gameObject = obj;
    --transform = obj.transform;
    if not obj then
        return
    end
    quality = obj:GetChild("quality")
    qualityBG = obj:GetChild("qualityBG")
    icon = obj:GetChild("icon")
    if not icon then
        icon = obj:GetChild("Icon")
    end
    --obj_element = transform:Find("bg_element").gameObject;
    --element = transform:Find("bg_element/element"):GetComponent("Image");
    lv = obj:GetChild("level")
    typeIcon = obj:GetChild("Occupation");
    typeShowController = obj:GetController("Occupation");
    --star = obj:GetChild("star")
    hasUse = obj:GetController("ctrlHadUsed")
    hadBattle = obj:GetController("ctrlHadBattle")
    hadAssist = obj:GetController("ctrlHadAssist")
    choose = obj:GetChild("maskChoose")
    unActive = obj:GetChild("unActive")
    emptyCtrl = obj:GetController("empty")
    banCtrl = obj:GetController("Ban")
    circletype = obj:GetController("CircleType")
    circleCtrl = obj:GetController("Circle")
    comIcon = obj:GetChild("Com_icon")
    useCtrl = obj:GetController("UseTime")
    useTxt = obj:GetChild("Text_UseTime")
    enemySelectCtrl = obj:GetController("HadSelect")
    levelShowCtrl = obj:GetController("isShowLevel")--0显示等级以及底框 1不显示
    typeCtrl = obj:GetController("Topicon")
    newCtrl = obj:GetController("new")
    hasCtrl = obj:GetController("ifHave")
    this.openController = obj:GetController("open")
    hasTxt = obj:GetChild("Text_NoOwn")
    manorCtrl = obj:GetController("Maner")
    if manorCtrl then
        manorCtrl.selectedIndex = 0;
    end
    if hothero then
        data["level"] = nil
        data["star"] = 150
    end
    if quality then
        quality.visible = false
        qualityBG.visible = false
    end
    if emptyCtrl then
        emptyCtrl.selectedIndex = 1
    end
    if circleCtrl then
        if circleCtrl.selectedIndex == 1 and circletype then
            circletype.selectedIndex = 0
        end
    end
    if useCtrl then
        useCtrl.selectedIndex = 0
    end
    if this.openController then
        this.openController.selectedIndex = 0
    end
    if enemySelectCtrl then
        enemySelectCtrl.selectedIndex = 0
    end
    if banCtrl then
        banCtrl.selectedIndex = 0
    end
    if  icon then
        icon.visible = false
    end

    if data then
        if emptyCtrl then
            emptyCtrl.selectedIndex = 0
        end
        if typeCtrl and data.faction then
            typeCtrl.selectedIndex = data.faction
        end
        if data["star"] ~= nil then
            data["quality"] = logicMgr.HeroManager.starToQuality(data["star"]);
        end
        if fightType == EnumConst.FightTypeConst.RankBattle then
            data["quality"] = 15
            local isban, isSeason = logicMgr.RankBattleManager.IsBan(data.partnerModelId, ismy)
            if banCtrl then
                if isban then
                    if isSeason then
                        banCtrl.selectedIndex = 1
                    else
                        if not notShowBan then
                            banCtrl.selectedIndex = 2
                        else
                            banCtrl.selectedIndex = 0
                        end
                    end
                else
                    banCtrl.selectedIndex = 0
                end
            end
            if not notShowBan then
                if circleCtrl and circleCtrl.selectedIndex == 1 then
                    if circletype then
                        if isSeason then
                            circletype.selectedIndex = 1
                        else
                            circletype.selectedIndex = 2
                        end
                    end
                end
            end
            if useCtrl then
                if logicMgr.HeroManager.NotHaveByModeId(data.partnerModelId) then
                    local num = logicMgr.RankBattleManager.HeroUsed(data.partnerModelId) or 0;
                    local max = G.dataTable["t_global"]["221"].f_int_value
                    if max - num <= 0 then
                        useCtrl.selectedIndex = 2
                    else
                        useCtrl.selectedIndex = 1
                    end
                    useTxt.text = (max - num) .. "/" .. max
                else
                    useCtrl.selectedIndex = 0
                end
            end
            if logicMgr.RankBattleManager.BanPick() and enemySelectCtrl then
                if logicMgr.RankBattleManager.BPCanChooseHeroByModelId(data.partnerModelId) and (not notShowBan) then
                    enemySelectCtrl.selectedIndex = 1
                else
                    enemySelectCtrl.selectedIndex = 0
                end
            end
        end
        --obj_element:SetActive(false);
        if levelShowCtrl then
            levelShowCtrl.selectedIndex = 1;
        end
        --star:SetActive(false);
        if (obj:GetController("Bar") ~= nil) then
            obj:GetController("Bar").selectedIndex = 0
        end
        if (obj:GetController("cost") ~= nil) then
            obj:GetController("cost").selectedIndex = 0
        end
        if (obj:GetController("new") ~= nil) then
            this.newController = obj:GetController("new");
            this.newController.selectedIndex = 0;
        else
            this.newController = nil;
        end
        if (obj:GetController("SSR") ~= nil) then
            this.showSSRController = obj:GetController("SSR");
            this.showSSRController.selectedIndex = 0;
        else
            this.showSSRController = nil;
        end
        if (obj:GetController("herodead") ~= nil) then
            this.herodeadController = obj:GetController("herodead");
            this.herodeadController.selectedIndex = 0;
        else
            this.herodeadController = nil;
        end
        if iswish then
            if newCtrl then
                if logicMgr.HeroManager.IsNewHero(nil, data.partnerModelId) then
                    newCtrl.selectedIndex = 1
                else
                    newCtrl.selectedIndex = 0
                end
            end
            if hasCtrl then
                if logicMgr.HeroManager.NotHaveByModeId(data.partnerModelId) then
                    hasCtrl.selectedIndex = 1
                    hasTxt.text = getLanguage("Draw_WishList_Tips2")
                else
                    hasCtrl.selectedIndex = 0
                end
            end
        end
        if hasUse then
            hasUse:SetSelectedIndex(0)
        end
        if  hadBattle then
            hadBattle:SetSelectedIndex(0)
        end
        if hadAssist then
            hadAssist:SetSelectedIndex(0)
        end
        if  choose then 
            choose.visible = false
        end
        if unActive then
            unActive.visible = false
        end
        

        if data ~= nil then
            --table_Star = {};
            --for i = 0, 4 do
            --    local objstar = obj:GetChild("star" .. i)
            --    table.insert(table_Star, objstar);
            --end
            if not isHopePool and levelShowCtrl ~= nil then
                if data["level"] ~= nil and tonumber(data["level"]) > 0 then
                    if levelShowCtrl then
                        levelShowCtrl.selectedIndex = 0;
                    end
                    local level, lvType = logicMgr.HeroManager.getHeroShowLevelByPartnerId(data.partnerId);
                    if level~=0 then
                        lv.text = string.TextColor(string.format(getLanguage("Level"), level), logicMgr.HeroManager.lvColors[lvType]);
                    else
                        lv.text = string.format(getLanguage("Level"), data["level"]);
                    end
                else
                    --不显示等级和等级底框
                    if levelShowCtrl then
                        levelShowCtrl.selectedIndex = 1;
                    end
                end
            end
            if fightType == EnumConst.FightTypeConst.RankBattle then
                if levelShowCtrl then
                    levelShowCtrl.selectedIndex = 0;
                end
                if levelShowCtrl then
                    levelShowCtrl.selectedIndex = 0;
                end
                lv.text = string.format(getLanguage("Level"), 300);
            elseif fightType == EnumConst.FightTypeConst.DarkStreet then
                if levelShowCtrl then
                    levelShowCtrl.selectedIndex = 0;
                end
                lv.text = string.format(getLanguage("Level"), dataTable.getGlobalInt(398));
            elseif fightType == EnumConst.FightTypeConst.ARENA then
                if levelShowCtrl then
                    levelShowCtrl.selectedIndex = 0;
                end
                if formation_type ~= nil then
                    if formation_type == EnumConst.FormationType.TeamCrossArenaDef 
                        or formation_type == EnumConst.FormationType.TeamCrossArenaAtk then  
                        lv.text = string.format(getLanguage("Level"), dataTable.getGlobalInt(491) or 300)
                    end
                end
            end
            --for i = 1, 5 do
            --    table_Star[i].visible = false
            --end
            if tonumber(data["star"]) ~= nil and tonumber(data["star"]) > 0 then
                --star:SetActive(true);
                local numstar = math.floor(data["star"] * 0.0001);
                if numstar > 5 then
                    numstar = 5;
                end
                --for i = 1, numstar do
                --    table_Star[i].visible = true
                --end
            end
            if data["halfIcon"] ~= nil then
                icon.visible = true
                if data.skinId and tonumber(data.skinId) > 0 then
                    icon:GetChild("icon").url = "ui://HalfBodyAtlas/" ..logicMgr.SkinManager.GetHeroBIconBySkinId(data.skinId)
                else
                    icon:GetChild("icon").url = "ui://HalfBodyAtlas/" .. data["halfIcon"]
                end
            end
            if data["icon"] ~= nil then
                local path = data["icon"];
                if data.skinId and tonumber(data.skinId) > 0 then
                    path = logicMgr.HeroManager.GetHeroIconByModelId(data.partnerModelId,data.skinId);
                end
                if circleCtrl and circleCtrl.selectedIndex == 1 then
                    comIcon.visible = true
                    comIcon:GetChild("icon").url = "ui://ICONAtlas/" .. path
                else
                    icon.visible = true
                    icon:GetChild("icon").url = "ui://ICONAtlas/" .. path
                end
                icon.visible = true
                icon:GetChild("icon").url = "ui://ICONAtlas/" .. path
                --resMgr:LoadIconFromPrefab("ICONAtlas", data["icon"],function(sp)
                --    icon.gameObject:SetActive(true);
                --    icon.sprite = sp;
                --end);
                if data["quality"] == nil or data["quality"] == 0 then
                    data["quality"] = 1;
                elseif data["quality"] > #tab_quality then
                    data["quality"] = #tab_quality;
                end
                if quality then
                    quality.visible = true
                    qualityBG.visible = true
                    quality.url = "ui://ICONAtlas/" .. tab_frame[data["quality"]]
                    qualityBG.url = "ui://ICONAtlas/" .. tab_quality[data["quality"]]
                end
                --resMgr:LoadIconFromPrefab("ICONAtlas",tab_frame[data["quality"]],function(sp)
                --    quality.gameObject:SetActive(true);
                --    quality.sprite = sp;
                --end);
                --resMgr:LoadIconFromPrefab("ICONAtlas",tab_quality[data["quality"]],function(sp)
                --    qualityBG.gameObject:SetActive(true);
                --    qualityBG.sprite = sp;
                -- end);
            end
            if typeShowController ~= nil then
                if data["type"] ~= nil then
                    typeShowController.selectedIndex = 0;
                    typeIcon.url = "ui://ICONAtlas/" .. EnumConst.HeroTypeIcon[data["type"]];
                else
                    typeShowController.selectedIndex = 1;
                end
            end
            if not notState then
                if data["state"] ~= nil then
                    if fightType == EnumConst.FightTypeConst.GuildBoss then
                        if data["state"] == EnumConst.GuildStateType.Battle or data["state"] == EnumConst.GuildStateType.HelpBattle then
                            hadBattle:SetSelectedIndex(1)
                        else
                            hadBattle:SetSelectedIndex(0)
                        end
                    else
                        if not isHopePool then
                            if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.SELECTED) > 0 then
                                choose.visible = true
                            else
                                choose.visible = false
                            end
                            if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.USED) > 0 then
                                hasUse:SetSelectedIndex(1)
                            else
                                hasUse:SetSelectedIndex(0)
                            end
                            if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.BATTLE) > 0 then
                                if fightType and (fightType == EnumConst.FormationType.FriendDefend or fightType == EnumConst.FormationType.FriendAttack) then
                                    if logicMgr.FriendBattleManager.HeroIsMy(fightType, data.partnerModelId) or logicMgr.FriendBattleManager.IsGoBattle(data.partnerModelId) then
                                        hadBattle:SetSelectedIndex(1)
                                    else
                                        hadBattle:SetSelectedIndex(0)
                                    end
                                else
                                    hadBattle:SetSelectedIndex(1)
                                end
                            else
                                if fightType and (fightType == EnumConst.FormationType.FriendDefend or fightType == EnumConst.FormationType.FriendAttack) then
                                    local ismy= logicMgr.FriendBattleManager.IsGoBattle(data.partnerModelId)
                                    if ismy then
                                        hasUse:SetSelectedIndex(1)
                                    else
                                        hasUse:SetSelectedIndex(0)
                                    end
                                end
                                hadBattle:SetSelectedIndex(0)
                            end
                            --if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.ASSIST) > 0 then
                            --    hadAssist:SetSelectedIndex(1)
                            --else
                            --    hadAssist:SetSelectedIndex(0)
                            --end
                        end
                        if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.UnActive) > 0 then
                            unActive.visible = true
                        else
                            unActive.visible = false
                        end
                        if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.DEAD) > 0 and not iswish then
                            obj.grayed = true;
                        else
                            obj.grayed = false;
                        end
                    end
                else
                    if  hadBattle then
                        hadBattle:SetSelectedIndex(0)
                    end         
                end
            end
            if data["new"] ~= nil and this.newController ~= nil then
                this.newController.selectedIndex = 1;
            end
            if data["showSSR"] and this.showSSRController ~= nil then
                this.showSSRController.selectedIndex = 1;
            end
            if data["isDead"] and this.herodeadController ~= nil and not iswish then
                this.herodeadController.selectedIndex = 1;
            end
            if (not logicMgr.HeroManager.isOpenHeroAtlas(data.partnerModelId) or data["version"] == 2) and this.openController ~= nil then
                this.openController.selectedIndex = 1;
            end
            if data["leaseHero"] ~= nil then
                if lv ~= nil and data["level"] ~= nil then
                    lv.text = string.format(getLanguage("Level"), data["level"]);
                    if levelShowCtrl ~= nil then
                        levelShowCtrl.selectedIndex = 0;
                    end
                end
                if useCtrl ~= nil then
                    useCtrl.selectedIndex = 1;
                end
                if useTxt ~= nil then
                    useTxt.text = (data["limit"] - data["useTimes"]).."/"..data["limit"];
                end
            end
        end
    else
        typeShowController.selectedIndex = 1
    end
end
function HeadRectItem.UpdateHPMPBar(obj, hp, mp)
    local ctrlBar = obj:GetController("Bar")
    local hpBar = obj:GetChild("BloodBar")
    local mpBar = obj:GetChild("EnergyBar")
    ctrlBar.selectedIndex = 1
    hpBar.value = hp
    mpBar.value = mp
end
function HeadRectItem.UpdateCostPower(obj, max, min, now)
    min = min or 1;
    local costController = obj:GetController("cost")
    local Text_Cost = obj:GetChild("Text_Cost")
    if costController == nil or Text_Cost == nil then
        return ;
    end
    if now >= max then
        costController.selectedIndex = 3;
    elseif now < min then
        costController.selectedIndex = 2;
    else
        costController.selectedIndex = 1;
    end
    Text_Cost.text = now .. "/" .. max;
end
---@param obj FairyGUI.GComponent
function HeadRectItem.updateState(obj, data, isGuild)
    --local transform = obj.transform;
    if not obj then
        return
    end
    if data["state"] ~= nil then
        if isGuild then
            local headStateCtrl = obj:GetController("state")
            hadBattle = obj:GetChild("hero"):GetController("ctrlHadBattle");
            if data["state"] == EnumConst.GuildStateType.UnBattle then
                headStateCtrl:SetSelectedIndex(1);
            else
                headStateCtrl:SetSelectedIndex(0);
            end
            if data["state"] == EnumConst.GuildStateType.Battle or data["state"] == EnumConst.GuildStateType.HelpBattle then
                hadBattle:SetSelectedIndex(1)
            else
                hadBattle:SetSelectedIndex(0)
            end
        else
            hasUse = obj:GetController("ctrlHadUsed");
            hadBattle = obj:GetController("ctrlHadBattle");
            hadAssist = obj:GetController("ctrlHadAssist");
            choose = obj:GetChild("maskChoose");
            unActive = obj:GetChild("unActive");

            hasUse:SetSelectedIndex(0)
            hadBattle:SetSelectedIndex(0)
            hadAssist:SetSelectedIndex(0)
            choose.visible = false
            unActive.visible = false
            if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.SELECTED) > 0 then
                choose.visible = true
            else
                choose.visible = false
            end
            if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.USED) > 0 then
                hasUse:SetSelectedIndex(1)
            else
                hasUse:SetSelectedIndex(0)
            end
            if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.BATTLE) > 0 then
                hadBattle:SetSelectedIndex(1)
            else
                hadBattle:SetSelectedIndex(0)
            end
            --if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.ASSIST) > 0 then
            --    hadAssist:SetSelectedIndex(1)
            --else
            --    hadAssist:SetSelectedIndex(0)
            --end
            if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.UnActive) > 0 then
                unActive.visible = true;
            else
                unActive.visible = false;
            end
            if ZZMathBit.andOp(data["state"], EnumConst.HeroHeadStateEnum.DEAD) > 0 then
                obj.grayed = true;
            else
                obj.grayed = false;
            end
        end
    end
end

function HeadRectItem.updateDecTitle(obj, data, type, isShow, fightType, formation_type)
    local controller = obj:GetController("Detail");
    controller.selectedIndex = type;
    local text = obj:GetChild("Detail");
    local levelText = obj:GetChild("level");
    if type == 0 then
        if not isShow then
            local lv, lvType = logicMgr.HeroManager.getHeroShowLevelByPartnerId(data.partnerId);
            levelText.text = string.TextColor(string.format(getLanguage("Level"), lv), logicMgr.HeroManager.lvColors[lvType]);
        else
            levelText.text = string.format(getLanguage("Level"), data["level"]);
        end
        if fightType == EnumConst.FightTypeConst.RankBattle then
            lv.text = string.format(getLanguage("Level"), 300);
        elseif fightType == EnumConst.FightTypeConst.DarkStreet then
            lv.text = string.format(getLanguage("Level"),dataTable.getGlobalInt(398))
        elseif fightType == EnumConst.FightTypeConst.ARENA then
            if formation_type ~= nil then
                if formation_type == EnumConst.FormationType.TeamCrossArenaDef 
                    or formation_type == EnumConst.FormationType.TeamCrossArenaAtk then  
                    lv.text = string.format(getLanguage("Level"), dataTable.getGlobalInt(491) or 300)
                end
            end
        end
        if data["leaseHero"] ~= nil then
            if lv ~= nil and data["level"] ~= nil then
                lv.text = string.format(getLanguage("Level"), data["level"]);
            end
        end
    else
        local decStr = getLanguage(G.dataTable["t_hero"][tostring(data["partnerModelId"])].f_HeroSubtext);
        text.text = decStr;
    end
end

function HeadRectItem.updateDebris(obj, data, type )
    local controller = obj:GetController("showDebris");
    local itemId = StrangeFragmentManager.GetCurrentEquipFragment(data.partnerId);
    local item = CtrlManager.GetCtrl(PanelNames.Item);

    if itemId then
        controller.selectedIndex = type and 1 or 0;
        if type then
            local itemBtn = obj:GetChild("debris")
            item.initData(itemBtn, itemId, 1, false, nil, data.partnerId);
            itemBtn.onClick:Clear();
        end
    else
        controller.selectedIndex = 0
    end
end

---@param go GComponent
function HeadRectItem.Empty(go)
    local ctrlEmpty = go:GetController("state")
    ctrlEmpty.selectedIndex = 0
end
function HeadRectItem.ShowLevel(obj, level)
    lv = obj:GetChild("level")
    levelShowCtrl = obj:GetController("isShowLevel")
    if level and level > 0 then
        levelShowCtrl.selectedIndex = 0;
        lv.text = string.format(getLanguage("Level"),level)
    else
        levelShowCtrl.selectedIndex = 1;
    end
end
function HeadRectItem.showManor(obj, partnerId)
    local manorCtrl = obj:GetController("Maner");
    if manorCtrl == nil then
        return
    end
    manorCtrl.selectedIndex = 0;
    local id = logicMgr.HeroManorManager.getManorMasterByGuest(partnerId);
    if id > 0 then
        local heroInfo = logicMgr.HeroManager.getHeroDatabyPartnerId(id, true);
        if heroInfo ~= nil then
            manorCtrl.selectedIndex = 1;
            local manorTips = obj:GetChild("manorTips");
            manorTips.text = string.format(getLanguage("HeroManorText06"), heroInfo.name);
        end
    end
end
return HeadRectItem;